package com.yny.administrator.android1607_meishi.thread;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;

import com.yny.administrator.android1607_meishi.cache.BitmapCache;
import com.yny.administrator.android1607_meishi.utils.HttpUtils;

import java.io.IOException;

/**
 * @author Administrator
 *         执行下载图片任务，并设置加载到图控件
 */
public class LoadImageTask extends AsyncTask<String, Void, Bitmap> {

    private ImageView mImage;
    private String image;

    public LoadImageTask(ImageView image, String img) {
        super();
        this.mImage = image;
        this.image = img;
    }

    @Override
    protected Bitmap doInBackground(String... params) {
        // TODO Auto-generated method stub
        try {
            byte[] res = HttpUtils.getHttpUtilsRes(params[0]);
            if (res != null) {
                Bitmap bitmap = BitmapFactory.decodeByteArray(res, 0, res.length);
                //进行缓存...
                if (bitmap != null) {
                    BitmapCache.getInstance().put(params[0], bitmap);
                }
                return bitmap;
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Bitmap result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        if (result != null && mImage != null) {
            mImage.setImageBitmap(result);
        }
    }
}
